<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Admin\BaseController;
use App\Http\Events\Admin\AdminEvent;
use App\Http\Model\Admin\User;
use Carbon\Carbon;
use Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class LoginController extends BaseController
{
    public function login(Request $request)
    {
        $input = Input::all();
        if ($input) {
            $validator = Validator::make($input, Config::get('admin.user.rules'), Config::get('admin.user.message'));
            if ($validator->passes()) {
                $new = new User();
                $user = $new->findOneByName($input['name']);
                if (Crypt::decrypt($user->password) == $input['password']) {
                    $user['last_login_ip'] = $request->ip();
                    session(['dmp_user' => $user]);
                    event(new AdminEvent('login'));
                    $new->updateOneById($user['id'], [
                        'last_login_ip' => $user['last_login_ip'],
                        'last_login_time' => Carbon::now()
                    ]);
                    return redirect('/admin/tourist');
                } else {
                    return back()->with('errors', '用户名或密码错误');
                }
            } else {
                return back()->withErrors($validator);
            }
        } else {
            return view('admin.login');
        }
    }

    public function logout()
    {
        session(['dmp_user' => null]);
        return redirect('/admin/login');
    }
}
